<template>
  <div class="roles-container">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表 -->
      <el-table :data="rolesList" border>
        <el-table-column type="expand">
          <!-- 权限展示 -->
          <template slot-scope="props">
            <div class="expand-box">
              <el-row :class="['b_botton', l0_index === 0 ? 'b_top' : '', 'aligncenter']" v-for="(l0_Item, l0_index) in props.row.children" :key="l0_Item.id">
                <!-- 一级权限 -->
                <el-col :span="5">
                  <el-tag>{{ l0_Item.authName }}</el-tag>
                </el-col>
                <el-col :span="19">
                  <!-- 二级权限 -->
                  <el-row v-for="(l1_Item, l1_index) in l0_Item.children" :key="l1_Item.id" :class="['aligncenter', l1_index === 0 ? '' : 'b_top']">
                    <el-col :span="6">
                      <el-tag type="success">{{ l1_Item.authName }}</el-tag>
                    </el-col>
                    <el-col :span="13">
                      <!-- 三级权限 -->
                      <el-tag type="warning" v-for="l2_Item in l1_Item.children" :key="l2_Item.id" closable @close="removeRight(props.row, l2_Item.id)">{{ l2_Item.authName }}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>

        <el-table-column type="index" label="#" width="50"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="290">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRoleMsg(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRole(scope.row)">删除</el-button>
            <el-button type="warning" icon="el-icon-key" size="mini" @click="editRightsTree(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible">
      <el-form ref="addRoleForm" :model="addRoleForm" label-width="auto" :rules="roleRules" status-icon>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRole()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑信息" :visible.sync="msgDialogVisible">
      <el-form ref="editRoleForm" :model="editRoleForm" label-width="auto" :rules="roleRules" status-icon>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="msgDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitNewMsg()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 权限树对话框 -->
    <el-dialog title="分配权限" :visible.sync="rightsTreeDialogVisible" @close="closeTreeDialog">
      <el-tree ref="treeRef" :data="rightsTree" :props="treeProps" show-checkbox :default-expand-all="true" node-key="id" :default-checked-keys="defKey"> </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsTreeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitNewRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      rolesList: [],
      rightsTree: [],
      rightsTreeDialogVisible: false,
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKey: [],
      roleId: '',
      // 编辑
      msgDialogVisible: false,
      roleRules: {
        roleName: [
          { required: true, message: '请输入新角色名', trigger: 'blur' },
          { min: 3, max: 7, message: '长度在 3 到 7 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      editRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色
      addDialogVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.rolesList = res.data
    },
    // 移除权限标签
    async removeRight(role, rightId) {
      const roleId = role.id
      const confirmResult = await this.$confirm('是否删除权限?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }

      const { data: res } = await this.$http.delete(`roles/${roleId}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        this.$message.eror(res.meta.msg)
      }

      role.children = res.data
      this.$message.success('已移除权限')
    },
    // 获取权限树
    async getRightsTree() {
      const { data: res } = await this.$http.get('rights/tree')
      console.log('权限树')
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }

      this.rightsTree = res.data
    },
    // 显示权限树编辑
    editRightsTree(role) {
      this.roleId = role.id
      this.getRightsTree()
      // 获取该角色已有的所有3级权限id
      this.getAllLevel3Id(role, this.defKey)
      this.rightsTreeDialogVisible = true
    },
    // 迭代获取所有角色已有的三级权限id
    getAllLevel3Id(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getAllLevel3Id(item, arr))
    },
    // 每次关闭权限树清空缓存的默认勾选数组
    closeTreeDialog() {
      // console.log('关闭')
      this.defKey = []
    },
    // 更新权限
    async submitNewRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]

      const rids = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: rids })

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.$message.success('修改成功')
      this.getRolesList()
      this.rightsTreeDialogVisible = false
    },
    // 编辑角色信息
    editRoleMsg(role) {
      this.roleId = role.id
      this.editRoleForm.roleName = role.roleName
      this.editRoleForm.roleDesc = role.roleDesc

      this.msgDialogVisible = true
    },
    // 提交新的角色信息
    async submitNewMsg() {
      const { data: res } = await this.$http.put(`roles/${this.roleId}`, this.editRoleForm)

      if (res.meta.status !== 200) {
        return this.$message.error(res.meat.msg)
      }

      this.getRolesList()
      this.$message.success('修改角色信息成功')
      this.msgDialogVisible = false
    },
    // 添加新角色
    async submitAddRole() {
      const { data: res } = await this.$http.post('roles', this.addRoleForm)

      if (res.meta.status !== 201) {
        return this.$message.error(res.meta.msg)
      }

      this.getRolesList()
      this.$message.success('添加成功')
      this.addDialogVisible = false
    },
    // 删除角色
    async removeRole(role) {
      const { data: res } = await this.$http.delete(`roles/${role.id}`)

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.getRolesList()
      this.$message.success('删除成功')
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 3px 3px;
}

.b_botton {
  border-bottom: 1px solid #ebeef5;
}

.b_top {
  border-top: 1px solid #ebeef5;
}

.aligncenter {
  display: flex;
  align-items: center;
}

.expand-box {
  padding: 10px 26px;
}
</style>
